<template>
  <div class="container">
    <div class="app-container">
      <!-- 组织架构 -->
      <el-tree default-expand-all :data="depts" :props="defaultProps">
        <template #default="{ data }">
          <el-row style="width: 100%">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="12">{{ data.managerName||'暂无' }}</el-col>
                <el-col :span="12">
                  <!-- 需要一个elementui 下拉菜单组件 -->
                  <!-- $event => 指代事件处理函数本身的参数 -->
                  <el-dropdown @command="handleCommand($event,data.id)">
                    <span>
                      操作
                      <i class="el-icon-arrow-down" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <!-- <el-dropdown-item @click.native="showAddDept=true">添加子部门</el-dropdown-item> -->
                        <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                        <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>

      <!-- <AddDept :show-add-dept="showAddDept" @updata:showAddDept="showAddDept.$event" /> -->
      <!-- <AddDept :show-add-dept.sync="showAddDept" /> -->
      <el-dialog :visible.sync="showAddDept" :title="title" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请选择">
              <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" placeholder="请输入" type="textarea" />
          </el-form-item>
          <!-- <el-form-item style="text-align: center" label-width="0px">
            <el-button type="primary">确定</el-button>
            <el-button>取消</el-button>
          </el-form-item> -->
        </el-form>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button>取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addDepartments, getDepartments, getManagerList, getDepartDetail, editDepartments, deleteDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
// import AddDept from './components/add-dept'
export default {
  name: 'Department',
  // components: { AddDept },
  data() {
    return {
      depts: [{
        // name: '传智教育',
        // children: [
        //   { name: '总裁办',
        //     children: [
        //       { name: '总裁办A部',
        //         children: [
        //           { name: '总裁办A1部' },
        //           { name: '总裁办A2部' }
        //         ]
        //       },
        //       { name: '总裁办B部',
        //         children: [
        //           { name: '总裁办B1部' },
        //           { name: '总裁办B2部' }
        //         ]
        //       }
        //     ]
        //   },
        //   { name: '行政部' },
        //   { name: '财务部' }
        // ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      List: [], // 备份一个部门列表数据 用于查询是否重复
      showAddDept: false,
      managerList: [],
      addForm: {
        name: '',
        managerId: '',
        code: '',
        introduce: ''
      }, // 添加部门的表单数据 字段和后端对齐
      rules: {
        name: [
          { required: true, message: '还不写吗？？？', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 新增时 和所有人比 this.List
              // 编辑时 和除了自己以外的所有人比 this.List.filter(自己出去)
              // this.addForm.id 有就是编辑 没有就是新增
              let temp = this.List
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id)
              }
              if (temp.some(item => item.name === value)) {
                callback(new Error('和已有部门的名字重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '还不写吗？？？', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '还不写吗？？？', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.List
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id)
              }
              if (temp.some(item => item.code === value)) {
                callback(new Error('和已有部门的编号重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        introduce: [
          { required: true, message: '还不写吗？？？', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      }, // 添加部门的规则
      parentId: null // 父部门的id(用于添加部门)
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getDepartments()
    this.getManagerList()
  },
  methods: {
    handleClose() {
      // this.$refs.addForm.resetFields()
      // 清除和页面没有绑定的字段
      this.addForm = {
        name: '',
        managerId: '',
        code: '',
        introduce: ''
      }
    },
    submit() {
      this.$refs.addForm.validate(async(isOK) => {
        if (isOK) {
          if (this.addForm.id) {
            // 编辑请求
            await editDepartments(this.addForm)
            this.$message.success('编辑成功')
          } else {
            // 新增请求
            await addDepartments({ ...this.addForm, pid: this.parentId })
            this.$message.success('添加成功')
          }

          this.getDepartments()
          this.showAddDept = false
          // this.$refs.addForm.resetFields()
          this.handleClose()
        }
      })
    },
    getManagerList() {
      getManagerList().then(res => {
        this.managerList = res
      })
    },
    handleCommand(type, id) {
      // console.log(type)
      if (type === 'add') {
        // 添加
        this.showAddDept = true
        this.parentId = id // 存一下这个部门的id => 这是即将添加的子部门的pid
      }
      if (type === 'edit') {
        // 编辑
        this.showAddDept = true
        this.parentId = id
        this.getDepartDetail()
      }
      if (type === 'del') {
        // 删除
        this.parentId = id
        // this.deleteDepartment()
        this.$confirm('此操作将永久删除该部门, 是否继续?', '警告', {
          confirmButtonText: '废话',
          cancelButtonText: '算了',
          type: 'warning'
        }).then(() => {
          this.deleteDepartment()
        }).catch(() => {
          console.log('取消了')
        })
      }
    },
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.getDepartments()
      this.$message.success('删除成功')
    },
    async getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      // console.log(res)
      // 回显 将后端返回的详情数据 赋值 给表单  表单和页面做了双绑
      this.addForm = res
    },
    async getDepartments() {
      const res = await getDepartments()
      this.List = res
      // console.log('财务部子部门', this.getChildrenDepart(res, 5))
      // console.log('技术部子部门', this.getChildrenDepart(res, 6))
      // console.log('市场部子部门', this.getChildrenDepart(res, 8))
      // console.log('传智部子部门', this.getChildrenDepart(res, 1))
      // this.depts = this.getChildrenDepart(res, 1)
      this.depts = transListToTreeData(res, 0)
    }
    /**
     * 获取指定部门的子部门
     * @param list 部门列表数据
     * @param departId 指定部门Id
     */
    // getChildrenDepart(list, departId) {
    //   // return list.filter(item => item.id === departId)
    //   const arr = []

    //   list.forEach(item => {
    //     if (item.pid === departId) {
    //       // ！！！！每找到一个子部门 带着这个子部门item.id 继续找他的子部门（调用自己这个函数即可）
    //       item.children = this.getChildrenDepart(list, item.id)// 加入arr之前 找一下item的子部门
    //       arr.push(item) // 将总裁办加入arr中 表示总裁办是传智教育的子部门
    //     }
    //   })
    //   return arr
    // }
  }
}
</script>
